package com.hdu.priority;

import java.util.Comparator;
import java.util.concurrent.*;

public class PriorityThreadPool extends ThreadPoolExecutor {
    public PriorityThreadPool(int corePoolSize, int maximumPoolSize,
                              long keepAliveTime, TimeUnit unit
    ) {
        super(
                corePoolSize, maximumPoolSize,
                keepAliveTime, unit,
                new PriorityBlockingQueue<>(100, new PriorityRunnableComparator())
        );
    }

    public void execute(Runnable runnable, int priority) {
        execute(PriorityRunnable.of(runnable, priority));
    }

    private static class PriorityRunnableComparator implements Comparator<Runnable> {

        @Override
        public int compare(Runnable o1, Runnable o2) {
            if (o1 instanceof PriorityRunnable && o2 instanceof PriorityRunnable) {
                return ((PriorityRunnable) o1).getPriority() - ((PriorityRunnable) o2).getPriority();
            } else {
                return 0;
            }
        }
    }
}
